package cn.agiledata.bank.common.service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.account.service.IAccountService;
import cn.agiledata.bank.common.bean.DisplayBean;
import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.dao.ActionTypeTemplate;
import cn.agiledata.bank.common.dao.BankTemplate;
import cn.agiledata.bank.common.dao.SysTemplate;
import cn.agiledata.bank.common.dao.TransactionListPage;
import cn.agiledata.bank.common.dao.TransactionTemplate;
import cn.agiledata.bank.common.exception.BusinessException;
import cn.agiledata.bank.common.form.BankBean;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.DateUtil;
import cn.agiledata.bank.common.util.OperateUtil;
import cn.agiledata.bank.common.util.PageBean;
import cn.agiledata.bank.common.util.SecurityUtil;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.UniqueIdentityUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.facade.helper.NotificationHelper;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AccountBank;
import cn.agiledata.bank.hibernateBean.AccountLimit;
import cn.agiledata.bank.hibernateBean.ActionType;
import cn.agiledata.bank.hibernateBean.BankInfo;
import cn.agiledata.bank.hibernateBean.Groups;
import cn.agiledata.bank.hibernateBean.ScoresHis;
import cn.agiledata.bank.hibernateBean.SubAccount;
import cn.agiledata.bank.hibernateBean.SysParameter;
import cn.agiledata.bank.hibernateBean.Sysbook;
import cn.agiledata.bank.hibernateBean.Transaction;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import cn.agiledata.bank.scores.service.IScoresService;
import cn.agiledata.bank.scores.service.ScoresFactory;
import cn.agiledata.bank.transaction.service.FeeRatioInterf;
import cn.agiledata.bank.transaction.service.GetTransaction;
import cn.agiledata.bank.transaction.service.GetTransactionImpl;
import cn.agiledata.bank.transaction.service.TransactionFactory;
import cn.agiledata.bank.wap.bean.HisAccountQueryBean;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class CommonServiceImpl implements ICommonService, Constant {
	private IAccountService accountService;

	private AccountTemplateInter accountTemplate;

	private ActionTypeTemplate actionTypeTemplate;

	private BankTemplate bankTemplate;

	private NotificationHelper notification;

	private FeeRatioInterf fri;

	private IMySpaceService mySpaceService;

	private TransactionTemplate transactionTemplate;

	public void setMySpaceService(IMySpaceService mySpaceService) {
		this.mySpaceService = mySpaceService;
	}

	public void setTransactionTemplate(TransactionTemplate transactionTemplate) {
		this.transactionTemplate = transactionTemplate;
	}

	/**
	 * 用户登录
	 * 
	 * @param from
	 *            来源 WEB方式--Constant.WEB;WAP方式--Constant.WAP;CALL
	 *            CENTER方式--Constant.CALL_CENTER
	 * @param loginname
	 *            WEB方式--手机/email;WAP方式--手机;CALL CENTER方式--客户编号
	 * @param operatorId
	 *            WEB方式--企业客户操作员;WAP方式----null;CALL CENTER方式--null
	 * @param password
	 *            WEB方式--登陆密码;WAP方式----登陆密码;CALL CENTER方式--IVR登陆密码
	 * @return
	 * @throws BusinessException
	 */
	public AccountSummary userLogon(String from, Map map)
			throws BusinessException {
		return accountService.userLogon(from, map);
	}

	/**
	 * 提现,账户付款共用
	 * 
	 * @param from
	 * @param map
	 * @throws BusinessException
	 */
	public Transaction transfer(String from, String step, Map map)
			throws BusinessException {
		Transaction tran = null;
		String accountId = (String) map.get("accountId"); // wap:账户id;call
		// center:账户accountId
		String subAccountId = (String) map.get("subAccountId"); // wap:子账户id
		String payPassword = (String) map.get("payPassword"); // wap:支付密码;call
		// center:IVR支付密码
		String bankName = (String) map.get("bankName"); // 所属银行
		String bankNo = (String) map.get("bankNo"); // 卡号
		String money = (String) map.get("money"); // 金额
		String name = (String) map.get("name"); // 姓名
		String actionType = (String) map.get("actionType"); // 交易类型:提现,帐户直付

		if (StringUtil.isStrEmpty(bankNo)) { // 卡号为空
			throw BusinessException.BANKNO_EMPTY;
		}
		if (StringUtil.isStrEmpty(money)) { // 金额为空
			throw BusinessException.MONEY_EMPTY;
		}
		if (StringUtil.isStrEmpty(payPassword)) { // 支付密码为空
			throw BusinessException.PAY_PASSWORD_EMPTY;
		}
		// <=0
		if (OperateUtil.isLowerThan(money, 0.0, IS_LOWER_EQUAL)) {
			throw BusinessException.MONEY_FORMAT_ERROR;
		}
		if (!OperateUtil.isMoney(money)) { // 金额格式不对
			throw BusinessException.MONEY_FORMAT_ERROR;
		}

		Account account = null;
		if (from.equals(Constant.CALL_CENTER)) { // 如果是call
			// center方式,根据账户accountId得到account对象
			account = accountTemplate.getAccountByAccountId(accountId);
		} else { // 根据账户id得到account对象
			account = accountTemplate.getAccount(accountId);
		}
		if (account == null) { // 账户不存在
			throw BusinessException.LOGON_ACCOUNT_NOT_EXIST;
		}

		tran = new Transaction();
		tran.setActionType(getActionTypeById(Long.parseLong(actionType)));
		if (!StringUtil.isStrEmpty(money)) {
			tran.setAmount(new Double(money));
		}
		if (!StringUtil.isStrEmpty(bankName)) {
			tran.setBankSeq(new Long(bankName));
		}
		if (StringUtil.isStrEmpty(name)) {
			tran.setPersonName(account.getName());
		} else {
			tran.setPersonName(name);
		}
		tran.setCredit(getRemitAccount()); // 设置付款方
		tran.setTransStatus(Constant.TRANS_STATUS_TRANSACTIONSUCCESS);
		if (from.equals(Constant.CALL_CENTER)) {
			tran.setDebit(accountTemplate
					.getIvrSubAccountByAccountId(accountId)); // 设置收款方
			tran.setOperSource(CALL_CENTER); // 设置来源
			tran.setAccountBankSeq(bankNo); // 设置银行卡
			AccountBank ab = getAccountBankById(bankNo); // 设置卡号
			if (ab == null) {
				throw BusinessException.NOT_EXIST_RECEIVE_ACCOUNT;
			}
			if (!ab.getAccount().getAccountId().equals(accountId)) { // 不是同一个人的卡号
				throw BusinessException.NOT_EXIST_RECEIVE_ACCOUNT;
			}
			tran.setCardNo(ab.getAccountId()); // 设置卡号
			tran.setBankProvSeq(ab.getProvSeq());//设置开户行省份
			tran.setBankCitySeq(ab.getCitySeq());//设置开户行城市
			tran.setBankName(ab.getBankName());//设置开户行
			tran.setBankSeq(ab.getBankInfo().getId());//银行
		} else if (from.equals(Constant.WAP)) {
			tran.setDebit(getSubAccount(subAccountId)); // 设置收款方
			tran.setOperSource(WAP);// 设置来源
			tran.setCardNo(bankNo); // 设置卡号
		}

		// 余额不足
		if (compareAccountMoney(tran.getDebit().getId().toString(), tran
				.getAmount()) != 0) {
			throw BusinessException.BALANCE_NOT_ENOUGH;
		}

		// 金额限制
		AccountLimit al = transactionTemplate.getAcctlimit(tran.getDebit()
				.getAccount());
		if (tran.getDebit().getAccount().getAccountType().equals(
				Constant.ACCOUNT_TYPE_BUYER)) {
			if (transactionTemplate.ifHigher(tran.getDebit().getAccount(), tran
					.getAmount().doubleValue(), al)) {
				throw BusinessException.AMOUNT_LIMIT_EXCEED;
			}
		}

		// 未经过交易,不能提现
		if (!isValidAmount(account, money)) {
			throw BusinessException.CAN_NOT_GAIN_MONEY;
		}

		// wap支付密码错误
		if (from.equals(Constant.WAP)) {
			// 如果支付密码正确
			if (!account.getPayPassword().equals(payPassword)) {
				throw BusinessException.PAY_PASSWORD_ERROR;
			}
		}

		if (step.equals(Constant.STEP_FIRST)) { // 如果是第一阶段
			tran.setDebitFee(new Double(fri.getDebitFee(tran))); // 设置付款人费率
			tran.setScoresAmount("0");
			tran.setTotalScores("0");
		} else if (step.equals(Constant.STEP_CONFIRM)) { // 如果是确认阶段
			if (from.equals(Constant.CALL_CENTER)) {
				// ivr支付密码错误
				if (!account.getIvrPayPassword().equals(payPassword)) {
					throw BusinessException.PAY_PASSWORD_ERROR;
				}
			}
			UniqueIdentityUtil uiu = new UniqueIdentityUtil();
			tran
					.setTransId(uiu.getTransactionSequence(
							Constant.ACCOUNT_TYPE_BUYER,
							Constant.MODEL_TYPE_GAINMONEY));
			// 封装插入日期和修改日期
			WeatherUtil.fillCreateAndUpdateInfo(tran, accountId);

			tran.setBeginDate(new Date());
			GetTransaction getTran = new GetTransactionImpl();
			TransactionFactory tt = getTran.getTransaction(actionType);
			tt.saveTransaction(tran);
			String scoresSource = null;
			if (actionType.equals(Constant.ACTION_TYPE_D))
				scoresSource = Constant.SCORES_SOURCE_C;
			if (actionType.equals(Constant.ACTION_TYPE_G))
				scoresSource = Constant.SCORES_SOURCE_F;
			// 根据交易金额计算积分
			ScoresHis sh = new ScoresHis();
			IScoresService iss = ScoresFactory.getScoresService();
			sh = iss.saveScoresHistory(account.getId().toString(), iss
					.getScoresRule(scoresSource, account.getId().toString()
							.toString()), tran, null);
			tran.setScoresAmount(String.valueOf(sh.getScoresAmount()));
			tran.setTotalScores(String.valueOf(sh.getTotalScores()));
		}
		return tran;
	}

	/**
	 * 付款
	 * 
	 * @param from
	 * @param map
	 * @throws BusinessException
	 */
	public Transaction vnvpayment(String from, String step, Map map)
			throws BusinessException {
		String receiveAccountName = (String) map.get("receiveAccountName"); // wap:收款方email/手机;call
		// center:收款方accountId
		if (!StringUtil.isStrEmpty(receiveAccountName)) {
			receiveAccountName = receiveAccountName.toLowerCase();
		}
		String money = (String) map.get("money"); // 金额
		String payPassword = (String) map.get("payPassword"); // wap:支付密码；call
		// center:IVR支付密码
		String subAccountId = (String) map.get("subAccountId"); // wap:子账户id
		String accountId = (String) map.get("accountId"); // wap:账户id;call
		// center:账户accountId

		if (StringUtil.isStrEmpty(receiveAccountName)) { // 收款方账号为空
			throw BusinessException.RECEIVE_ACCOUNT_EMPTY;
		}
		if (StringUtil.isStrEmpty(money)) { // 金额为空
			throw BusinessException.MONEY_EMPTY;
		}
		if (StringUtil.isStrEmpty(payPassword)) { // 支付密码为空
			throw BusinessException.PAY_PASSWORD_EMPTY;
		}

		/** ***************账户不存在******************* */
		Account account = null;
		if (from.equals(Constant.CALL_CENTER)) { // 如果是call
			// center方式,根据账户accountId得到account对象
			account = accountTemplate.getAccountByAccountId(accountId);
		} else { // 根据账户id得到account对象
			account = accountTemplate.getAccount(accountId);
		}
		if (account == null) { // 账户不存在
			throw BusinessException.LOGON_ACCOUNT_NOT_EXIST;
		}
		/** ***************账户不存在******************* */

		/** ***************收款方账户不存在******************* */
		Account receiveAccount = null;
		if (from.equals(Constant.CALL_CENTER)) { // 如果是call
			// center方式,根据收款方账户accountId得到account对象
			receiveAccount = accountTemplate
					.getAccountByAccountId(receiveAccountName);
		} else { // 根据收款方账户email/手机得到account对象
			receiveAccount = accountService
					.findAccountByEmail(receiveAccountName);
		}
		if (receiveAccount == null) { // 收款方账户不存在
			throw BusinessException.RECEIVE_ACCOUNT_NOT_EXIST;
		} else {
			if(Constant.ACCOUNT_TYPE_INITIAL.equals(receiveAccount.getAccountType())) {//如果是内部账户,报收款方账户不存在
				throw BusinessException.RECEIVE_ACCOUNT_NOT_EXIST;
			}
		}
		/** ***************收款方账户不存在******************* */

		/** ****************付款操作失败您选择的交易双方重复********************* */
		if (account.getId().toString()
				.equals(receiveAccount.getId().toString())) { //
			throw BusinessException.SAME_PERSON;
		}
		/** ****************付款操作失败您选择的交易双方重复********************* */

		// 付款对象不是能正常使用的账户
		if (!ifOthersAvailable(receiveAccount)) {
			throw BusinessException.RECEIVE_ACCOUNT_NOT_ACTIVE;
		}

		if (!OperateUtil.isMoney(money)) { // 金额格式不对
			throw BusinessException.MONEY_FORMAT_ERROR;
		}
		// <=0
		if (OperateUtil.isLowerThan(money, 0.0, IS_LOWER_EQUAL)) {
			throw BusinessException.MONEY_FORMAT_ERROR;
		}

		Transaction tran = new Transaction();
		tran.setActionType(getActionTypeById(Long
				.parseLong(Constant.ACTION_TYPE_C)));
		tran.setAmount(new Double(money)); // 交易金额
		WeatherUtil.fillCreateAndUpdateInfo(tran, accountId); // 封装插入日期和修改日期
		tran.setPersonName(receiveAccountName);
		tran.setTradeType(TRADE_TYPE_NOASSURE); // 无担保交易
		tran.setTransStatus(TRANS_STATUS_TRANSACTIONSUCCESS);
		tran.setOperate(MODEL_TYPE_PAYMONEY);
		if (from.equals(Constant.CALL_CENTER)) { // call center
			tran.setDebit(accountTemplate
					.getIvrSubAccountByAccountId(accountId)); // 付款方,IVR子账户
			receiveAccount.getDefaultSubAccount().setAccount(receiveAccount);
			tran.setCredit(receiveAccount.getDefaultSubAccount()); // 收款方,至默认子账户
			tran.setOperSource(CALL_CENTER);
		} else if (from.equals(Constant.WAP)) { // wap
			tran.setDebit(getSubAccount(subAccountId)); // 付款方
			tran.setCredit(receiveAccount.getDefaultSubAccount()); // 收款方,至默认子账户
			tran.setOperSource(WAP);
		}
		/** ****************余额不足******************** */
		if (compareAccountMoney(tran.getDebit().getId().toString(), tran
				.getAmount()) != 0) { // 余额不足
			throw BusinessException.BALANCE_NOT_ENOUGH;
		}
		/** ****************余额不足******************** */

		/** ***************支付密码不正确******************* */
		if (from.equals(Constant.WAP)) { // call center
			if (!account.getPayPassword().equals(payPassword)) { // 查看支付密码是否正确
				throw BusinessException.PAY_PASSWORD_ERROR;
			}
		}
		/** ***************支付密码不正确******************* */

		if (step.equals(Constant.STEP_FIRST)) { // 如果是第一阶段

			tran.setDebitFee(new Double(fri.getDebitFee(tran))); // 设置付款人费率
		} else if (step.equals(Constant.STEP_CONFIRM)) { // 如果是确认阶段
			if (from.equals(Constant.CALL_CENTER)) { // call center
				if (!account.getIvrPayPassword().equals(payPassword)) { // 如果是ivr，查看IVR支付密码是否正确
					throw BusinessException.PAY_PASSWORD_ERROR;
				}
			}
			UniqueIdentityUtil uiu = new UniqueIdentityUtil();
			tran
					.setTransId(uiu.getTransactionSequence(
							Constant.ACCOUNT_TYPE_BUYER,
							Constant.MODEL_TYPE_GATHERING));
			tran.setBeginDate(new Date());
			GetTransaction getTran = new GetTransactionImpl();
			TransactionFactory tt = getTran
					.getTransaction(Constant.ACTION_TYPE_C);
			tt.saveTransaction(tran);
		}

		return tran;
	}

	/**
	 * 
	 * @param from
	 */
	public void loginPasswordMofify(String from, String accountId,
			String password) {
		Account account = null;
		if (from.equals(Constant.CALL_CENTER)) { // 如果是call
			// center方式,根据账户accountId得到account对象
			account = accountTemplate.getAccountByAccountId(accountId);
		} else { // 根据账户id得到account对象
			account = accountTemplate.getAccount(accountId);
		}
		if (account == null) { // 账户不存在
			throw BusinessException.LOGON_ACCOUNT_NOT_EXIST;
		}
		if (StringUtil.isStrEmpty(password)) { // 登陆密码为空
			throw BusinessException.LOGIN_PASSWORD_EMPTY;
		}
		if (password.length() < 6) { // 密码太短
			throw BusinessException.PASSWORD_TOO_SHORT;
		}
		if (from.equals(Constant.CALL_CENTER)) {
			account.setIvrLoginPassword(password);
		} else if (from.equals(Constant.WAP)) {
			password = SecurityUtil.encryptoMD5String(password);
			account.setLoginPassword(password);
		}
		accountTemplate.updateAccount(account);
	}

	/**
	 * 
	 * @param from
	 */
	public void payPasswordMofify(String from, String accountId,
			String originPassword, String password) {
		Account account = null;
		if (from.equals(Constant.CALL_CENTER)) { // 如果是call
			// center方式,根据账户accountId得到account对象
			account = accountTemplate.getAccountByAccountId(accountId);
		} else { // 根据账户id得到account对象
			account = accountTemplate.getAccount(accountId);
		}
		if (account == null) { // 账户不存在
			throw BusinessException.LOGON_ACCOUNT_NOT_EXIST;
		}
		if (StringUtil.isStrEmpty(password)) { // 登陆密码为空
			throw BusinessException.LOGIN_PASSWORD_EMPTY;
		}
		if (password.length() < 6) { // 密码太短
			throw BusinessException.PASSWORD_TOO_SHORT;
		}
		if (from.equals(Constant.CALL_CENTER)) {
			if (!originPassword.equals(account.getIvrPayPassword())) { // 原登陆密码错误
				throw BusinessException.OLD_PAY_PASSWORD_ERROR;
			}

			account.setIvrPayPassword(password);
		} else if (from.equals(Constant.WAP)) {
			password = SecurityUtil.encryptoMD5String(password);
			account.setPayPassword(password);
		}
		accountTemplate.updateAccount(account);
	}

	/**
	 * 根据account对象的accountId得到ivr子账户
	 * 
	 * @param accountId
	 * @return
	 */
	public SubAccount getIvrSubAccountByAccountId(String accountId) {
		return accountTemplate.getIvrSubAccountByAccountId(accountId);
	}

	/**
	 * 
	 * @param accountId
	 * @param startPage
	 * @param perPage
	 * @return
	 */
	public PageBean getTransactionList(int startPage, int pageSize,
			long accountId) {
		TransactionListPage pl = new TransactionListPage(startPage, pageSize,
				accountId);

		PageBean pb = pl.getAccountListPageBean();

		return pb;
	}

	/**
	 * 根据收费模式判断交易金额是否为负数
	 */
	public int compareAmounts(String subAccountId, String actionType,
			Double amount) {
		int com = 0;
		SubAccount subAcc = accountTemplate.getSubAccount(subAccountId);
		Groups group = mySpaceService.getGroupByAccount(subAcc.getAccount(),
				Constant.GROUP_TYPE_A);
		double accBalance = subAcc.getAccountBalance().getBalance()
				.doubleValue();
		double fee = 0.00;
		if (Constant.ACTION_TYPE_A.equals(actionType)
                || Constant.ACTION_TYPE_B.equals(actionType)
                || Constant.ACTION_TYPE_F.equals(actionType)
                || Constant.ACTION_TYPE_K.equals(actionType)
                || Constant.ACTION_TYPE_L.equals(actionType)
                || Constant.ACTION_TYPE_O.equals(actionType)
                || Constant.ACTION_TYPE_P.equals(actionType)
				|| Constant.ACTION_TYPE_Q.equals(actionType)) {
			fee = fri.getCreditFee(null, subAcc.getAccount(), actionType,
					amount);
		} else {
			if(group.getId()!=null)
			{
			fee = fri.getDebitFee(subAcc, actionType, amount, group.getId()
					.toString());
			}
		}
		if (Constant.ACTION_TYPE_D.equals(actionType)
				|| Constant.ACTION_TYPE_G.equals(actionType)) {
			SysTemplate sysTemplate = (SysTemplate) IPBAppFactory
					.getObj("sysTemplate");
			SysParameter feeMode = sysTemplate.getWithDrawFee(new Long(
					subAccountId));
			if (Constant.WITHDRAW_FEE_FRIST.equals(feeMode.getParmValue())) {
				com = (accBalance - amount.doubleValue() - fee) >= 0 ? 0 : 2;
			}
			if (Constant.WITHDRAW_FEE_SECOND.equals(feeMode.getParmValue())) {
				com = (amount.doubleValue() - fee) > 0 ? 0 : 2;
			}
		}
		if (Constant.ACTION_TYPE_A.equals(actionType)
				|| Constant.ACTION_TYPE_B.equals(actionType)) {
			com = (amount.doubleValue() - fee) > 0 ? 0 : 2;
		}
		// 卡转账到或账户转账到卡时,如果手续费>=转账金额,不让用户转
		if (Constant.ACTION_TYPE_X.equals(actionType)
				|| Constant.ACTION_TYPE_Y.equals(actionType)) {
			com = (amount.doubleValue() - fee) > 0 ? 0 : 2;

			// 账户转账到卡时,如果子账户当前余额-转账金额-fee<0,不让用户转(返回值3，区别于手续费>=转账金额的返回值2)
			if (Constant.ACTION_TYPE_Y.equals(actionType)) {
				if (accBalance - amount.doubleValue() - fee >= 0 && amount.doubleValue() - fee > 0)
					com = 0;
				else
					com = 3;
			}
		}
		if (Constant.ACTION_TYPE_C.equals(actionType)) {// 账户间交易
			if (accBalance - amount.doubleValue() - fee >= 0 && amount.doubleValue() - fee > 0)
				com = 0;
			else
				com = 2;
			//com = (accBalance - amount.doubleValue() - fee) >= 0 ? 0 : 2;
		}

		return com;
	}

	/**
	 * 判断提现是否符合规定（充值超过规定天数后方可提现）
	 */
	public boolean isValidAmount(Account account, String amount) {
		double subAccBalance = 0;
		for (Iterator iter = account.getSubAccounts().iterator(); iter
				.hasNext();) {
			SubAccount sa = (SubAccount) iter.next();
			subAccBalance = subAccBalance
					+ sa.getAccountBalance().getBalance().doubleValue();
		}
		Sysbook sysbook = accountTemplate.getDateRestrictions();
		Date date = DateUtil.addDay(new Date(), -new Integer(sysbook.getId()
				.getListId()).intValue());
		// 限制天数前的账户余额
		Double accBalHis = accountTemplate.getAccBalHis(account
				.getSubAccounts(), DateUtil.date2String(date));
		// 限制天数内的充值总额
		Double charge = accountTemplate.getAmountByTransaction(account.getId()
				.toString(), DateUtil.date2String(date));
		// 限制天数内的收入总额
		Double revenue = accountTemplate.getRevenueByTransaction(account
				.getId().toString(), DateUtil.date2String(date));
		// 限制天数内的提现总额
		Double draw = accountTemplate.getDrawByTransaction(account.getId()
				.toString(), DateUtil.date2String(date));
		if (charge == null)
			charge = new Double(0.00);
		if (revenue == null)
			revenue = new Double(0.00);
		if (draw == null)
			draw = new Double(0.00);

		double total = new BigDecimal(subAccBalance - revenue.doubleValue()
				- charge.doubleValue()).setScale(2, BigDecimal.ROUND_HALF_UP)
				.doubleValue();

		double sum = 0.00;
		if (total >= 0) {
			sum = total + revenue.doubleValue();
		} else {
			sum = revenue.doubleValue() - draw.doubleValue()
					+ accBalHis.doubleValue();
		}
		if (new Double(amount).doubleValue() <= sum) {
			return true;
		} else {
			return false;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see cn.agiledata.bank.account.service.impl.III#userRegister(java.lang.String,
	 *      java.lang.String, java.lang.String, java.lang.String,
	 *      java.lang.String, java.lang.String)
	 */
	public void userRegister(String from, String project, Map map)
			throws BusinessException {
		try {
			accountService.userRegister(from, project, map);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void setNotification(NotificationHelper notification) {
		this.notification = notification;
	}

	public void setAccountTemplate(AccountTemplateInter accountTemplate) {
		this.accountTemplate = accountTemplate;
	}

	public void setAccountService(IAccountService accountService) {
		this.accountService = accountService;
	}

	public void setActionTypeTemplate(ActionTypeTemplate actionTypeTemplate) {
		this.actionTypeTemplate = actionTypeTemplate;
	}

	public void setBankTemplate(BankTemplate bankTemplate) {
		this.bankTemplate = bankTemplate;
	}

	public Account getAccount(String id) {
		return accountTemplate.getAccount(id);
	}

	public Account getAccountByAccountID(String id) {
		return accountTemplate.getAccountByAccountId(id);
	}

	public ActionType getActionTypeById(long id) {
		return actionTypeTemplate.getActionTypeById(id);
	}

	public SubAccount getSubAccount(String id) {
		return accountTemplate.getSubAccount(id);
	}

	public SubAccount getRemitAccount() {
		return accountTemplate.getRemitAccount();
	}

	public int compareAccountMoney(String SubAccountId, Double wantedCount) {
		return accountTemplate.compareAccountMoney(SubAccountId, wantedCount);
	}

	public BankInfo getBankInfo(String id) {
		return bankTemplate.getBankInfo(id);
	}

	public AccountBank getAccountBankByAccountIdAndBankName(String accountId,
			String bankName) {
		List list = accountTemplate.getAccountBankListByAccountIdAndBankName(
				accountId, bankName);
		if (list != null) {
			return (AccountBank) list.get(0);
		} else {
			return null;
		}
	}

	public void updateAccountBank(AccountBank accountBank) {
		bankTemplate.updateAccountBank(accountBank);
	}

	/**
	 * 
	 * @param accountSummary
	 * @return
	 */
	public SubAccount getWapSubAccount(AccountSummary accountSummary) {
		SubAccount returnSubAccount = null;
		List list = accountSummary.getSubAccountList();
		if (list != null) {
			Iterator iterator = list.iterator();
			while (iterator.hasNext()) {
				SubAccount subAccount = (SubAccount) iterator.next();
				if (subAccount != null) {
					long accountId = accountSummary.getAccountId();
					// 如果是该账户的wap账户
					if (subAccount.getAccount().getId().longValue() == accountId
							&& subAccount.getDetailFlag().equals(
									DETAIL_FLAG_TRUE)) {
						returnSubAccount = subAccount;
						break;
					}
				}
			}
		}
		return returnSubAccount;
	}

	/**
	 * 
	 * @param bean
	 * @return
	 */
	public PageBean getHisAccountQueryPagingList(HisAccountQueryBean bean) {
		// HisAccountQueryPageListPage listPage =
		// new HisAccountQueryPageListPage(bean);
		// PageBean pb = listPage.getAccountListPageBean();
		Map map = new HashMap();
		map.put("accountID", bean.getAccountId());
		if (bean.getStartDate() != null)
			map.put("beginDate", DateUtil.date2String(bean.getStartDate(),
					"yyyy-MM-dd"));
		if (bean.getEndDate() != null)
			map.put("endDate", DateUtil.date2String(bean.getEndDate(),
					"yyyy-MM-dd"));

		PageBean pb = mySpaceService.getAccountHisListPageBean(map, Integer
				.parseInt(bean.getStartPage()), new Long(1).intValue());
		return pb;
	}

	public Account findAccountBySign(String sign) {
		return accountService.findAccountByEmail(sign);
	}

	/**
	 * 
	 */
	public void userRegisterByWap(String loginPassword, String payPassword,
			String mobile, String username) throws BusinessException {
		accountService.userRegisterByWap(loginPassword, payPassword, mobile,
				username);
	}

	/**
	 * 
	 */
	public void updateAccount(Account account) {
		accountTemplate.updateAccount(account);
	}

	public void returnLoginPasswordBySMS(String mobile, Map context) {
		notification.returnLoginPasswordBySMS(mobile, context);
	}

	public void setFri(FeeRatioInterf fri) {
		this.fri = fri;
	}

	public FeeRatioInterf getFri() {
		return fri;
	}

	/**
	 * 判断交易对方是否是冻结账户或者是否被激活或者如果是企业用户的话是否通过审核
	 */
	public boolean ifOthersAvailable(Account account) {
		boolean ifAvailable;
		// 当account类型为个人用户的时候
		if (StringUtil.isStrEmpty(account.getMobile())) {
			if (account.getAccountType().equals(Constant.ACCOUNT_TYPE_BUYER))
				if (account.getStatus().equals(Constant.ACCOUNT_STATE_NORMAL)) {
					ifAvailable = true;
				} else {
					ifAvailable = false;
				}
			// 当account类型为企业用户的时候
			else if (account.getAccountType().equals(
					Constant.ACCOUNT_TYPE_CORPORATION)) {
				if (account.getStatus().equals(Constant.ACCOUNT_STATE_NORMAL)
						&& account.getAuditStatus().equals(
								Constant.ACCOUNT_AUDIT_STATUS_NORMAL)) {
					ifAvailable = true;
				} else {
					ifAvailable = false;
				}
			}
			// 当account不为个人用户和企业用户的时候，目前只有内部账户
			else {
				ifAvailable = true;
			}
		} else {
			if (account.getAccountType().equals(Constant.ACCOUNT_TYPE_BUYER))
				if (account.getStatus().equals(Constant.ACCOUNT_STATE_NORMAL)) {
					ifAvailable = true;
				} else {
					ifAvailable = true;
				}
			// 当account类型为企业用户的时候
			else if (account.getAccountType().equals(
					Constant.ACCOUNT_TYPE_CORPORATION)) {
				if (account.getStatus().equals(Constant.ACCOUNT_STATE_NORMAL)
						&& account.getAuditStatus().equals(
								Constant.ACCOUNT_AUDIT_STATUS_NORMAL)) {
					ifAvailable = true;
				} else {
					ifAvailable = false;
				}
			}
			// 当account不为个人用户和企业用户的时候，目前只有内部账户
			else {
				ifAvailable = true;
			}
		}
		return ifAvailable;

	}

	public SubAccount findSubAccountBalance(long AccountId, String subAccountId) {
		return accountService.findSubAccountBalance(AccountId, subAccountId);
	}

	public List accountList(String accountID) throws BusinessException {
		List list = mySpaceService.getAccountBankList(accountID);
		
		return list;
	}

	public AccountBank getAccountBankById(String id) {
		return bankTemplate.getAccountBankById(id);
	}

	public DisplayBean getDisplayName(String accountId) {
		DisplayBean db = new DisplayBean();
		if (Constant.ACCOUNT_TYPE_BUYER.equals(getAccount(accountId)
				.getAccountType())) {
			db.setFAccountType(Constant.FINANCIAL_USERTYPE_PERSONAL);
			db.setFAccountName(Constant.FINANCIAL_USERTYPE_PERSONAL_NUMBER);
			db.setButtonName(Constant.BUTTON_NAME_PERSONAL);
			db.setMsg1(Constant.INFORMATION_PERSONAL_1);
			db.setMsg2(Constant.INFORMATION_PERSONAL_2);
		} else {
			db.setFAccountType(Constant.FINANCIAL_CORP_OPERATOR);
			db.setFAccountName(Constant.FINANCIAL_CORP_OPERATOR_NUMBER);
			db.setButtonName(Constant.BUTTON_NAME_CORP);
			db.setMsg1(Constant.INFORMATION_CORP_1);
			db.setMsg2(Constant.INFORMATION_CORP_2);
		}
		return db;
	}

	public List getSubAccountList(String accountId) {
		// 默认子账户
		Account account = accountTemplate.getAccount(accountId);
		SubAccount defaultSA = account.getDefaultSubAccount();
		Set subAccountSet = account.getSubAccounts();

		List subAccountlist = new ArrayList();
		subAccountlist.add(defaultSA);

		Iterator it = subAccountSet.iterator();
		while (it.hasNext()) {
			SubAccount sa = (SubAccount) it.next();
			if (!defaultSA.getId().equals(sa.getId())) {
				subAccountlist.add(sa);
			} else {
				continue;
			}
		}
		return subAccountlist;
	}

	public List getBankList() {
		List list = new ArrayList();
		BankBean bean = new BankBean(Constant.BANK_A_NAME, Constant.BANK_A,
				Constant.BANK_A_NUMBER);
		list.add(bean);
		bean = new BankBean(Constant.BANK_B_NAME, Constant.BANK_B,
				Constant.BANK_B_NUMBER);
		list.add(bean);
		bean = new BankBean(Constant.BANK_C_NAME, Constant.BANK_C,
				Constant.BANK_C_NUMBER);
		list.add(bean);
		bean = new BankBean(Constant.BANK_D_NAME, Constant.BANK_D,
				Constant.BANK_D_NUMBER);
		list.add(bean);
		bean = new BankBean(Constant.BANK_E_NAME, Constant.BANK_E,
				Constant.BANK_E_NUMBER);
		list.add(bean);
		return list;
	}

	public BankBean getBankBeanById(String id) {
		List list = getBankList();

		// BankBean bean = new
		// BankBean(Constant.BANK_A_NAME,Constant.BANK_A,Constant.BANK_A_NUMBER);
		// if(Constant.BANK_A.equals(id))
		// return bean;
		// if(Constant.BANK_B.equals(id))
		// return new
		// BankBean(Constant.BANK_B_NAME,Constant.BANK_B,Constant.BANK_B_NUMBER);
		// if(Constant.BANK_C.equals(id))
		// return new
		// BankBean(Constant.BANK_C_NAME,Constant.BANK_C,Constant.BANK_C_NUMBER);
		// if(Constant.BANK_D.equals(id))
		// return new
		// BankBean(Constant.BANK_D_NAME,Constant.BANK_D,Constant.BANK_D_NUMBER);
		// return bean;
		for (int i = 0; i < list.size(); i++) {
			BankBean bean = (BankBean) list.get(i);
			if (id.equals(bean.getId())) {
				return bean;
			}
		}
		return (BankBean) list.get(0);
	}

}
